import express from 'express';
import Ret, { RetCode } from '../../bean/code/Ret';
const app = express();
import { db, Sequelize } from '../../dao/config';
const Administrator = require("../../dao/models/b_administrator")(db, Sequelize);
import md5 from 'md5'


/**
 * 管理员登录
 */
// 发起 POST /api/login 请求完成用户登录，并添加该用户到 req.session.authUser
app.post('/admin/login', async function (req, res) {
  const {userName, password} = req.body;
  try {
    const administrator = await Administrator.find({where: {phone: userName}});
    if (administrator != null) {
      if (md5(password) === administrator.password) {
        req.session.authUser = administrator;
        return res.json({status: 200, administrator});
      } else {
        return res.json({status: 500, msg: "密码错误！"});
      }
    }
    return res.json({status: 500, msg: "账号不存在！"});

  } catch (e) {
    res.status(500).json({error: '错误请求！'})
  }
});

// 发起 POST /api/logout 请求注销当前用户，并从 req.session 中移除
app.post('/admin/logout', function (req, res) {
  delete req.session.authUser;
  return res.json({ok: true})
});

export default app;
